package com.ruoyi.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class MintTest {

    @Autowired
    private JavaMailSender mailSender;

    public static void main(String[] args) throws Exception {

        String[] split = new String[]{"123","345"};
        JSONObject id = new JSONObject();
        id.put("registration_id",split);
        JSONObject message = new JSONObject();
        message.put("msg_content","登记成功");
        JSONObject extra = new JSONObject();
        extra.put("action","声音提醒");
        extra.put("actionType","声音");
        extra.put("content","京Q1234523");
        message.put("extras",extra);
        JSONObject send = new JSONObject();
        send.put("platform","all");
        send.put("audience",id);
        send.put("message",message);
        JSONObject options = new JSONObject();
        options.put("time_to_live", 0);
        send.put("options",options);
        System.out.println("推送消息"+send.toJSONString());


//        String str = "鲁BAF3059";
//        String str2 = "鲁B7173L";
//        System.out.println(str.substring(0,3)+(str.length()==8?"****":"***")+str.substring(str.length()-1));
//        System.out.println(str2.substring(0,3)+(str2.length()==8?"****":"***")+str2.substring(str2.length()-1));

//        List<DjbDistrict> djbDistricts = new ArrayList<>();
//        for(int j=10;j>1;j--){
//            DjbDistrict tmp = new DjbDistrict();
//            tmp.setDistance(j*1000);
//            djbDistricts.add(tmp);
//        }
//        djbDistricts.sort((o1, o2) -> {
//            Integer name1 = o1.getDistance();//name1是从你list里面拿出来的一个
//            Integer name2 = o2.getDistance();//name1是从你list里面拿出来的一个
//            return name1.compareTo(name2);
//        });
//        Date monthBegin = DateUtils.getMonthBegin();
//        System.out.println("");
//        List<String> jgIdList = new ArrayList<>();
//        for(int i =0;i<10;i++){
//            jgIdList.add("设备ID"+i);
//        }
//        String jgId = String.join(",",jgIdList);
//        String[] split = jgId.split(",");
//        JSONObject id = new JSONObject();
//        id.put("registration_id",split);
//        JSONObject notification = new JSONObject();
//        JSONObject put = new JSONObject();
//        put.put("alert", "");
//        JSONObject extra = new JSONObject();
//        extra.put("action","自动抬杆");
//        extra.put("actionType","放行");
//        extra.put("registryId",123);
//        put.put("extras",extra);
//        notification.put("android",put);
//        JSONObject put2 = new JSONObject();
//        put2.put("alert", "");
//        JSONObject extra2 = new JSONObject();
//        extra2.put("action","自动抬杆");
//        extra2.put("actionType","放行");
//        extra2.put("registryId",123);
//        put2.put("extras",extra2);
//        notification.put("ios",put2);
//        notification.put("alert","自动抬杆");
//        JSONObject send = new JSONObject();
//        send.put("platform","all");
//        send.put("audience",id);
//        send.put("notification",notification);
//        send.put("options",new JSONObject().put("time_to_live",0));
//        System.out.println(send.toJSONString());
    }

    /*处理用户空号检测结果不显示闪退等问题*/
    public static void handleEmptyCheck(){
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("X:\\empty_res.txt"), "utf-8"));
            String str =reader.readLine();
            JSONArray ret = JSONArray.parseArray(str);
            JSONArray sh =new JSONArray();
            StringBuilder sb = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            for(int i=0;i<ret.size();i++){
                Byte status = ret.getJSONObject(i).getByte("status");
                if (status == 1) {
                    sb2.append(ret.getJSONObject(i).getString("mobile")).append(" 实号").append("\r\n");
                    sb.append(ret.getJSONObject(i).getString("mobile")).append("\r\n");
                }else if (status == 0){
                    sb2.append(ret.getJSONObject(i).getString("mobile")).append(" 空号").append("\r\n");
                }else if (status == 2){
                    sb2.append(ret.getJSONObject(i).getString("mobile")).append(" 停机").append("\r\n");
                }else {
                    sb2.append(ret.getJSONObject(i).getString("mobile")).append(" 沉默风险号").append("\r\n");
                }
            }
            File file1 =new File("D:\\检测数据-详情.txt");
            if(!file1.exists()){
                file1.createNewFile();
            }
            File file2 =new File("D:\\检测结果-实号.txt");
            if(!file2.exists()){
                file2.createNewFile();
            }
            FileWriter fw1 = new FileWriter(file1.getAbsoluteFile());
            BufferedWriter bw1 = new BufferedWriter(fw1);
            bw1.write(sb2.toString());
            bw1.close();

            FileWriter fw2 = new FileWriter(file2.getAbsoluteFile());
            BufferedWriter bw2 = new BufferedWriter(fw2);
            bw2.write(sb.toString());
            bw2.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*空号检测*/
    public static void emptyPhoneCheck() throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("X:\\1234.txt"), StandardCharsets.UTF_8));//GBK
        String line;
        StringBuilder sb = new StringBuilder();
        while((line=reader.readLine())!=null ){
            if(line.length() != 11||!line.startsWith("1")||!line.matches("[0-9]+"))continue;
            sb.append(line).append(",");
        }
        String mobiles =sb.substring(0,sb.length()-1);
        String[] mobile_arr= mobiles.split(",");
        int cost = mobile_arr.length;
        StringBuilder mobile_b=new StringBuilder();
        JSONArray ret = new JSONArray();
        for(int i=0;i<cost;i++){
            String tmp = mobile_arr[i];
            mobile_b.append(tmp).append(",");
            if((i%49==0 && i!=0)||(i==cost-1)){
                String send =mobile_b.substring(0,mobile_b.length()-1);
                // 1.调用api
                JSONObject jsonObject =JSONObject.parseObject(HttpUtils.httpPostString("https://api.253.com/open/unn/batch-ucheck","appId=BHvTVz91&appKey=nyyZVwlc&mobiles="+send));
                // 2.处理返回结果
                String code = jsonObject.getString("code");
                if ("200000".equals(code) && jsonObject.get("data") != null) {
                    ret.addAll(jsonObject.getJSONArray("data"));
                }
                /*重置mobile_b*/
                mobile_b= new StringBuilder();
                System.out.println(i);
            }
        }
        try {
            StringBuilder sb1 = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            for(int i=0;i<ret.size();i++){
                Byte status = ret.getJSONObject(i).getByte("status");
                if (status == 1) {
                    sb2.append(ret.getJSONObject(i).getString("mobile")).append(" 实号").append("\r\n");
                    sb1.append(ret.getJSONObject(i).getString("mobile")).append("\r\n");
                }else if (status == 0){
                    sb2.append(ret.getJSONObject(i).getString("mobile")).append(" 空号").append("\r\n");
                }else if (status == 2){
                    sb2.append(ret.getJSONObject(i).getString("mobile")).append(" 停机").append("\r\n");
                }else {
                    sb2.append(ret.getJSONObject(i).getString("mobile")).append(" 沉默风险号").append("\r\n");
                }
            }
            File file1 =new File("X:\\检测数据-详情.txt");
            if(!file1.exists()){
                file1.createNewFile();
            }
            File file2 =new File("X:\\检测结果-实号.txt");
            if(!file2.exists()){
                file2.createNewFile();
            }
            FileWriter fw1 = new FileWriter(file1.getAbsoluteFile());
            BufferedWriter bw1 = new BufferedWriter(fw1);
            bw1.write(sb2.toString());
            bw1.close();

            FileWriter fw2 = new FileWriter(file2.getAbsoluteFile());
            BufferedWriter bw2 = new BufferedWriter(fw2);
            bw2.write(sb1.toString());
            bw2.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void handleUser3() throws Exception{
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("x:\\result.txt"), StandardCharsets.UTF_8));//GBK
        String line;
        String id ;
        int idx;
        int douhao_idx;
        List<String> list = new ArrayList<>();
        while((line=reader.readLine())!=null ){
            if(!line.startsWith("ID"))continue;
            idx=line.indexOf("id:");
            douhao_idx=line.indexOf("mobile",idx);
            id=line.substring(idx+3,douhao_idx);
            if(list.contains(id))continue;
            list.add(id);
            System.out.println(id);
        }

        System.out.println("DONE~~~~~~~~~~~~~~~~~~~~~~~~~");
    }

    public  void testMail(){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("13061386060@163.com");
        message.setTo("18201182896@163.com");
        message.setSubject("测试邮件发送");
        message.setText("邮件正文");
        mailSender.send(message);
    }

    private void checkNum() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("X:\\111.txt"), StandardCharsets.UTF_8));//GBK
        String line;
        String phone;
        String name;
        String tmp;
        Pattern pattern = Pattern.compile("[0-9]*");
        while((line=reader.readLine())!=null ){
            System.out.println("old:"+line);
            if(!line.startsWith("0")&&!line.startsWith("1"))continue;
            line=line.replaceAll("\\s","").replaceAll("\t","").replaceAll("\n","").replaceAll("\r","");
            if(line.startsWith("1")){
                phone = line.substring(0,11);
                name = line.substring(11);
            }else{
                char c = line.charAt(4);
                if(String.valueOf(c).equals("-")){
                    phone = line.substring(0,13);
                    name = line.substring(13);
                }else{
                    phone = line.substring(0,12);
                    name = line.substring(12);
                }
            }
            /*判断是否只包含纯数字*/
            tmp =phone.replace("-","");
            if(!pattern.matcher(tmp).matches()){
                System.out.println("wrong:"+phone);
                continue;
            }
            System.out.println("phone:"+phone);
            System.out.println("name:"+name);
        }
    }

    private static void readExcel() throws IOException{
        File file = new File("X:\\0805.xlsx");
        /*
         * 表格格式：第一列号码，第二列名称
         * */
        InputStream is = new FileInputStream(file);
        String fileName = file.getName();
        Workbook workbook;
        if(fileName.endsWith("xls")){
            workbook = new HSSFWorkbook(is);
        }else if(fileName.endsWith("xlsx")){
            workbook = new XSSFWorkbook(is);
        }else{
            System.out.println("tag error");
            return;
        }
        //读取工作簿的第一张表格
        Sheet sheet = workbook.getSheetAt(0);
        Row row;
        String phone;
        String name;
        String tmp;
        int index=0;
        Pattern pattern = Pattern.compile("[0-9]*");
        /*默认第一行是标题行*/
        for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); i++) {
            row = sheet.getRow(i);
            int physicalNumberOfCells = row.getPhysicalNumberOfCells();
            for (int j=0;j<physicalNumberOfCells;j++){
                // 读取单元格内容
                phone = getCellValue(row.getCell(j));
                phone =phone.replaceAll("\\s","").replaceAll("\t","").replaceAll("\n","").replaceAll("\r","");
                if(phone.length()!=11){
                    continue;
                }
                if(phone.matches("^[1][3,4,5,7,8,9][0-9]{9}$")){
                    System.out.println(phone);
                    index++;
                }
//                String regex="1[35789]\\d{9}";
//                String regex2="[1][3,5,7,8,9]\\d{9}";
//                Pattern p = Pattern.compile(regex);
//                Matcher m = p.matcher(phone);
//
//                while (m.find()){
//                    phone=m.group();
//                    System.out.println("正确号码:"+phone);
//                    index++;
//                }
//                System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            }
        }
        System.out.println(":"+index);
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if ("NUMERIC".equals(cell.getCellType().name())) {
            return BigDecimal.valueOf(cell.getNumericCellValue()).toString();
        } else if ("STRING".equals(cell.getCellType().name()))
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        else if ("FORMULA".equals(cell.getCellType().name())) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if ("BLANK".equals(cell.getCellType().name())) {
            return "";
        } else if ("BOOLEAN".equals(cell.getCellType().name())) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if ("ERROR".equals(cell.getCellType().name())) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }


}